package com.yunshipei.common;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;

import com.yunshipei.EnterApplication;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.db.EnterplorerHelper;
import com.yunshipei.manager.EnterDbManager;
import com.yunshipei.manager.EnterMailManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.NotifyInfo;
import com.yunshipei.model.UserInfo;
import com.yunshipei.ui.dialog.CommonDialog;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.AlarmSet;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.EncUtils;

import java.io.File;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.rong.app.utils.StringUtilSub;

public class ExitApps {
    private Context context;
    private UserInfo userInfo;

    public ExitApps(Context context) {
        this.context = context;
        this.userInfo = (UserInfo) StringUtilSub.getEncodeBase64(YspPreferences.getInstance().getSharedPreferences().getString(Globals.YSP_USER_INFO, ""));
    }

    public void showConfirm() {
        CommonDialog commonDialog = new CommonDialog(context);
        commonDialog.setTitle("提示");
        commonDialog.setMessage("确定安全退出吗?");
        commonDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        commonDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                exitApps();
                YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.USER_NAME, "").putString(Globals.PASSWORD, "")
                        .commit();
            }
        });
        commonDialog.show();
    }

    public void exitApps() {
        final WaitDialog waitDialog = DialogHelper.getNoCancelableWaitDialog(context, "正在擦除本地数据,请稍候...");
        waitDialog.show();
        //安全退出三星等其他机型需要清空badge数字
        try {
            EnterMailManager.getInstance().exitEnterEmail(context); //清空邮箱数据
            String imMessageFolder = "";
            closeAllNotify();
            imMessageFolder = StringUtilSub.getApplicationMeteData(context, context.getPackageName(), "RONG_CLOUD_APP_KEY");
            final String path = context.getFilesDir().getParent();
            context.deleteDatabase(EnterplorerHelper.DB_NAME);
            final String finalImMessageFolder = imMessageFolder;
            Flowable.create(new FlowableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(FlowableEmitter<Boolean> e) throws Exception {
                    EnterDbManager.getInstances().delete();
                    BaseUtil.deletePathReal(path + "/app_KeyStore");
                    BaseUtil.deletePathReal(path + "/app_webview");
                    BaseUtil.deletePathReal(path + "/app_xwalkcore");
                    BaseUtil.deletePathReal(path + "/cache");
                    BaseUtil.deletePathReal(path + "/code_cache");
                    BaseUtil.deletePathReal(path + "/app_database");
                    BaseUtil.deletePathReal(path + "/web_contacts");
                    BaseUtil.deletePathReal(path + "/web_me");
                    BaseUtil.deletePathReal(Environment.getExternalStorageDirectory() + File.separator + "yunshipei" + File.separator + "log");
                    //安全退出不删除聊天记录
                    deleteExcept(path + "/files", finalImMessageFolder);
                    deleteExcept(path + "/databases", "");
                    deletePreference(path + "/shared_prefs");
                    e.onNext(true);

                }
            }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            waitDialog.dismiss();
                            EnterApplication.getApp().onTerminate();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            waitDialog.dismiss();
                            EnterApplication.getApp().onTerminate();
                        }
                    });
        } catch (Exception ignored) {
            waitDialog.dismiss();
            EnterApplication.getApp().onTerminate();
        }
    }

    private void closeAllNotify() {
        List<NotifyInfo> list;
        DatabaseUtil dbu = new DatabaseUtil();
        AlarmSet alarmSet = new AlarmSet(this.context);
        list = dbu.queryNotifiAll(true, userInfo.getUuid());
        for (NotifyInfo aList : list) {
            alarmSet.cancelAlarm(aList);
        }
    }

    private void deleteExcept(String path, String... args) {
        File file = new File(path);
        if (file.exists() && file.isDirectory()) {
            File[] tempFiles = file.listFiles();
            for (File tempFile : tempFiles) {
                String name = tempFile.getName();
                boolean delete = true;
                for (String arg : args) {
                    if (name.equals(arg)) {
                        delete = false;
                        break;
                    }
                }
                if (!delete) continue;
                BaseUtil.deletePathReal(tempFile.getPath());
            }
        }
    }

    @SuppressLint({"CommitPrefEdits", "ApplySharedPref"})
    private void deletePreference(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] spFiles = file.listFiles();
            for (File spFile : spFiles) {
                String name = spFile.getName();
                String spName = name.substring(0, name.indexOf(".xml"));
                if ("_ysp_h5_cfg".equals(spName) || Globals.NO_CLEAR_SHP.equals(spName)) {
                    continue;
                }
                EnterApplication.getApp().getSharedPreferences(spName, Context.MODE_PRIVATE).edit().clear().commit();
            }
        }
    }
}
